﻿/*
============================================================================
文件名    ： StringHelper.cs
完全限定名： M_NET.Common.StringHelper
作者      ： 陈存腾
创建时间  ： 2012-03-18
修改时间  ： 
版本      ：
说明      ： 基础辅助类－字符串相关
============================================================================
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace M_NET.Common
{
    /// <summary>
    /// 字符串辅助
    /// </summary>
    public class StringHelper
    {
        #region string与List<string>相互转换

        /// <summary>
        /// 把字符串以空格为分隔符转换成 List
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <returns>转换得到的List</returns>
        public static List<string> StringToList(string str)
        {
            return StringToList(str, ' ', false);
        }

        /// <summary>
        /// 把字符串按照分隔符转换成 List
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="speater">分隔符</param>
        /// <param name="toLower">是否转换为小写</param>
        /// <returns>转换得到的List</returns>
        public static List<string> StringToList(string str, char speater, bool toLower)
        {
            List<string> list = new List<string>();
            string[] strArray = str.Split(speater);
            foreach (string s in strArray)
            {
                if (!string.IsNullOrEmpty(s) && s != speater.ToString())
                {
                    string strVal = s;
                    if (toLower)
                    {
                        strVal = s.ToLower();
                    }
                    list.Add(strVal);
                }
            }
            return list;
        }

        /// <summary>
        /// 把 List 以空格为分隔符格式化成 string
        /// </summary>
        /// <param name="list">待转换的List</param>
        /// <returns>目标字符串</returns>
        public static string ListToString(List<string> list)
        {
            return ListToString(list, " ");
        }

        /// <summary>
        /// 把 List 按照分隔符格式化成 string
        /// </summary>
        /// <param name="list">待转换的List</param>
        /// <param name="speater">分隔符</param>
        /// <returns>目标字符串</returns>
        public static string ListToString(List<string> list, string speater)
        {
            if (list.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                // 依次添加List中的各个字符串
                foreach (string s in list)
                {
                    sb.Append(s + speater);
                }
                // 删除末尾的分隔符
                sb.Remove(sb.Length - speater.Length, speater.Length);
                return sb.ToString();
            }
            else
            {
                return "";
            }
        }

        #endregion

        #region string与Dictionary相互转换

        /// <summary>
        /// 把 Dictionary 格式化成 string
        /// 键和值之间以“:”隔开，键值对之间以“,”隔开
        /// </summary>
        /// <param name="list">待转换的Dictionary</param>
        /// <returns>目标字符串</returns>
        public static string DictionaryToString(Dictionary<string, object> dictionary)
        {
            if (dictionary.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                // 依次添加Dictionary中的各个键值对
                foreach (KeyValuePair<string, object> kvp in dictionary)
                {
                    sb.Append(String.Concat(kvp.Key, ':', kvp.Value, ','));
                }
                // 删除末尾的分隔符
                sb.Remove(sb.Length - 1, 1);
                return sb.ToString();
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 把字符串按照分隔符转换成 Dictionary
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="toLower">是否转换为小写</param>
        /// <returns>转换得到的 Dictionary</returns>
        public static Dictionary<string, object> StringToDictionary(string str, bool toLower)
        {
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            string[] kvp = null;
            foreach (string s in str.Split(','))
            {
                if (!string.IsNullOrEmpty(s) && s != ",")
                {
                    kvp = s.Split(':');
                    if (!string.IsNullOrEmpty(kvp[0]))
                    {
                        dictionary[kvp[0]] = kvp[1];
                    }
                }
            }
            return dictionary;
        }

        #endregion

        #region 字符串剪裁

        /// <summary> 
        /// 将指定字符串按指定长度进行剪切， 
        /// </summary> 
        /// <param name="oldStr">需要截断的字符串</param> 
        /// <param name="maxLength">字符串的最大长度</param> 
        /// <param name="endWith">超过长度的后缀</param> 
        /// <returns> 如果超过长度，返回截断后的新字符串加上后缀，否则，返回原字符串 </returns> 
        public static string StringTruncat(string oldStr, int maxLength, string endWith)
        {
            if (string.IsNullOrEmpty(oldStr))
            {
                // throw new NullReferenceException( "原字符串不能为空 "); 
                return oldStr;
            }
            if (maxLength < 1)
            {
                throw new Exception("返回的字符串长度必须大于[0] ");
            }
            if (oldStr.Length > maxLength)
            {
                string strTmp = oldStr.Substring(0, maxLength);
                if (string.IsNullOrEmpty(endWith))
                {
                    return strTmp;
                }
                else
                {
                    return strTmp + endWith;
                }
            }
            return oldStr;
        }

        /// <summary>
        /// 删除最后结尾的一个逗号
        /// </summary>
        public static string DelLastComma(string str)
        {
            return str.Substring(0, str.LastIndexOf(","));
        }

        /// <summary>
        /// 删除最后结尾的指定字符后的字符
        /// </summary>
        public static string DelLastChar(string str, string strchar)
        {
            return str.Substring(0, str.LastIndexOf(strchar));
        }

        #endregion

        #region 全角/半角转换

        /// <summary>
        /// 转全角的函数(SBC case)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ToSBC(string input)
        {
            //半角转全角：
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char)12288;
                    continue;
                }
                if (c[i] < 127)
                {
                    c[i] = (char)(c[i] + 65248);
                }
            }
            return new string(c);
        }

        /// <summary>
        ///  转半角的函数(SBC case)
        /// </summary>
        /// <param name="input">输入</param>
        /// <returns></returns>
        public static string ToDBC(string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                {
                    c[i] = (char)(c[i] - 65248);
                }
            }
            return new string(c);
        }

        #endregion

        #region “[key]:[value],”字符串格式化解码

        /// <summary>
        /// 从字符串中提取值，格式为…[key]:[value],…
        /// </summary>
        /// <param name="str">包含信息的字符串</param>
        /// <param name="key">键</param>
        /// <returns>值</returns>
        public static string GetValueByKey(string str, string key)
        {
            int i = str.IndexOf(key);
            int j;
            string val = null;
            if (i != -1)
            {
                i = str.IndexOf(":", i);
                if (i == -1)
                {
                    return null;
                }
                j = str.IndexOf(",", i);
                if (j == -1)
                {
                    return null;
                }
                val = str.Substring(i + 1, j - i - 1);
            }
            return val;
        }

        /// <summary>
        /// 从字符串中提取值，格式为…[key]:[value],…
        /// </summary>
        /// <param name="str">包含信息的字符串</param>
        /// <param name="key">键</param>
        /// <param name="hasUnderline">是否包含下划线“_”转义符</param>
        /// <returns>值</returns>
        public static string GetValueByKey(string str, string key, bool hasUnderline)
        {
            int i = str.IndexOf(key);
            int j;
            string val = null;
            if (i != -1)
            {
                i = str.IndexOf(":", i);
                if (i == -1)
                {
                    return null;
                }
                j = str.IndexOf(",", i);
                if (j == -1)
                {
                    return null;
                }
                if (hasUnderline)
                {
                    val = DecodeByChar(str.Substring(i + 1, j - i - 1), '_');
                }
                else
                {
                    val = str.Substring(i + 1, j - i - 1);
                }
            }
            return val;
        }

        /// <summary>
        /// 从字符串中提取值，格式为…[key]:[value],…
        /// </summary>
        /// <param name="str">包含信息的字符串</param>
        /// <param name="key">键</param>
        /// <returns>值</returns>
        public static int GetIntByKey(string str, string key)
        {
            int i = str.IndexOf(key);
            int j;
            string val = null;
            if (i != -1)
            {
                i = str.IndexOf(":", i);
                if (i == -1)
                {
                    return 0;
                }
                j = str.IndexOf(",", i);
                if (j == -1)
                {
                    return 0;
                }
                val = str.Substring(i + 1, j - i - 1);
            }
            if (String.IsNullOrEmpty(val))
            {
                return 0;
            }
            else
            {
                return int.Parse(val);
            }
        }

        /// <summary>
        /// 从字符串中提取值，格式为…[key]:[value],…
        /// </summary>
        /// <param name="str">包含信息的字符串</param>
        /// <param name="key">键</param>
        /// <returns>值</returns>
        public static DateTime GetDateTimeByKey(string str, string key)
        {
            int i = str.IndexOf(key);
            int j;
            string val = null;
            if (i != -1)
            {
                i = str.IndexOf(":", i);
                if (i == -1)
                {
                    return DateTime.MinValue;
                }
                j = str.IndexOf(",", i);
                if (j == -1)
                {
                    return DateTime.MinValue;
                }
                val = str.Substring(i + 1, j - i - 1);
            }
            if (String.IsNullOrEmpty(val))
            {
                return DateTime.MinValue;
            }
            else
            {
                return DateTime.Parse(val);
            }
        }

        /// <summary>
        /// 把字符串格式化为[key]:[value],
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="str">值</param>
        /// <returns>[tag]:[value],</returns>
        public static string SetValueByKey(string key, string val)
        {
            if (!String.IsNullOrEmpty(val))
            {
                return String.Concat(key, ':', val, ',');
            }
            return null;
        }

        /// <summary>
        /// 把字符串格式化为[key]:[value],
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="str">值</param>
        /// <param name="hasUnderline">是否对下划线“_”进行转义</param>
        /// <returns>[tag]:[value],</returns>
        public static string SetValueByKey(string key, string val, bool hasUnderline)
        {
            if (!String.IsNullOrEmpty(val))
            {
                if (hasUnderline)
                {
                    return String.Concat(key, ':', EncodeByChar(val, '_'), ',');
                }
                else
                {
                    return String.Concat(key, ':', val, ',');
                }
            }
            return null;
        }

        /// <summary>
        /// 把字符串格式化为[key]:[value],
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="str">值</param>
        /// <param name="hasUnderline">是否对下划线“_”进行转义</param>
        /// <returns>&lt;{0}&gt;{1}&lt;/{0}&gt;</returns>
        public static string SetXMLValueByKey(string key, string val, bool hasUnderline)
        {
            if (!String.IsNullOrEmpty(val))
            {
                if (hasUnderline)
                {
                    return String.Format("<{0}>{1}</{0}>", key, EncodeByChar(val, '_'));
                }
                else
                {
                    return String.Format("<{0}>{1}</{0}>", key, val);
                }
            }
            return null;
        }

        #endregion

        #region 编码转义

        #region 对字符串中的指定单个字符进行转义

        /// <summary>
        /// 对指定字符进行转义编码
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="esc">待转义的字符</param>
        /// <returns>经过转义编码后的字符串</returns>
        public static string EncodeByChar(string str, char esc)
        {
            return str.Replace(esc.ToString(), string.Concat('\\', esc));
        }

        /// <summary>
        /// 对已经进行字符转义编码的字符串解码
        /// </summary>
        /// <param name="str">被转义的字符串</param>
        /// <param name="esc">转义的字符</param>
        /// <returns>源字符串</returns>
        public static string DecodeByChar(string str, char esc)
        {
            return str.Replace(string.Concat('\\', esc), esc.ToString());
        }

        ///// <summary>
        ///// 以下划线“_”为转义字符，对字符串转义编码
        ///// </summary>
        ///// <param name="str">源字符串</param>
        ///// <returns>经过转义编码后的字符串</returns>
        //public static string EncodeByUnderline(string str)
        //{
        //    return EncodeByChar(str, '_');
        //}

        ///// <summary>
        ///// 以下划线“_”为转义字符，对字符串解码
        ///// </summary>
        ///// <param name="str">被转义的字符串</param>
        ///// <returns>源字符串</returns>
        //public static string DecodeByUnderline(string str)
        //{
        //    return DecodeByChar(str, '_');
        //}

        #endregion

        #endregion

    }
}
